// src/recipe-detail/RecipeComments.tsx
import React, { useState, useEffect } from 'react';
import { Card, List, Avatar, Button, Spin, message, Input, Tooltip, Popconfirm } from 'antd';
import { Typography } from 'antd';
import { LikeOutlined, LikeFilled, DeleteOutlined } from '@ant-design/icons';

const { Title } = Typography;
const { Text } = Typography;

interface Comment {
  id: number;
  user: {
    id: number;
    username: string;
    avatar: string;
  };
  content: string;
  likeCount: number;
  createdAt: string;
  isLiked?: boolean;
}

interface RecipeCommentsProps {
  recipeId: number;
  colorConfig?: {
    primary: string;
    primaryDark: string;
    border: string;
    background: string;
    badge: string;
    tabActive: string;
  };
}

const RecipeComments: React.FC<RecipeCommentsProps> = ({ recipeId, colorConfig }) => {
  const [comments, setComments] = useState<Comment[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [commentContent, setCommentContent] = useState<string>('');
  const [likeLoading, setLikeLoading] = useState<{ [commentId: number]: boolean }>({});
  const [deleteLoading, setDeleteLoading] = useState<{ [commentId: number]: boolean }>({});

  // 默认颜色配置
  const defaultColorConfig = {
    primary: '#e8d9c7',
    primaryDark: '#8b4513', 
    border: '#d4b896',
    background: '#f8f4f0',
    badge: '#a0522d',
    tabActive: '#e8d9c7',
  };

  const colors = colorConfig || defaultColorConfig;

  // 获取当前用户ID
  const getCurrentUserId = (): number | null => {
    const userId = localStorage.getItem('userId');
    return userId ? parseInt(userId) : null;
  };

  // 完整的时间格式化函数
  const formatDate = (dateStr: string | undefined): string => {
    if (!dateStr || dateStr === 'string' || dateStr === 'LocalDateTime.now()') {
      return '未知时间';
    }
    
    try {
      let date = new Date(dateStr);
      
      if (isNaN(date.getTime())) {
        let cleanStr = dateStr;
        
        if (cleanStr.includes('T') && !cleanStr.includes('Z') && !cleanStr.includes('+')) {
          cleanStr += 'Z';
        }
        
        if (cleanStr.includes(' ') && !cleanStr.includes('T')) {
          cleanStr = cleanStr.replace(' ', 'T');
          if (!cleanStr.includes('Z') && !cleanStr.includes('+')) {
            cleanStr += 'Z';
          }
        }
        
        date = new Date(cleanStr);
      }
      
      if (isNaN(date.getTime())) {
        return '未知时间';
      }
      
      const formattedDate = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
      
      return formattedDate;
      
    } catch (error) {
      return '未知时间';
    }
  };

  // 检查用户是否点赞了评论
  const checkCommentLikes = async (comments: Comment[]) => {
    const currentUserId = getCurrentUserId();
    if (!currentUserId) return comments;

    try {
      const token = localStorage.getItem('token');
      if (!token) return comments;

      const response = await fetch(`/api/recipecommentlike/all`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const userLikes = await response.json();
        return comments.map(comment => ({
          ...comment,
          isLiked: Array.isArray(userLikes) && userLikes.some((like: any) => 
            like.commentId === comment.id && like.userId === currentUserId
          )
        }));
      }
    } catch (error) {
      console.error('检查评论点赞状态失败:', error);
    }

    return comments;
  };

  // 获取评论列表
  const fetchComments = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setComments([]);
        return;
      }

      const response = await fetch(`/api/recipecomment/by-recipe?recipeId=${recipeId}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        const commentsWithLikes = await checkCommentLikes(data);
        setComments(commentsWithLikes);
      } else {
        throw new Error(`接口返回 ${response.status} ${response.statusText}`);
      }
    } catch (error) {
      console.error('加载评论失败:', error);
      message.error('加载评论失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 发布评论
  const submitComment = async () => {
    if (!commentContent.trim()) {
      message.warning('请输入评论内容');
      return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
      message.info('请先登录');
      return;
    }

    setSubmitting(true);
    try {
      const currentUserId = getCurrentUserId();
      if (!currentUserId) {
        message.error('无法获取用户信息');
        return;
      }

      const requestBodies = [
        {
          recipe: {
            id: recipeId
          },
          user: {
            id: currentUserId
          },
          content: commentContent.trim(),
          replyToUserId: 0,
          likeCount: 0
        },
        {
          recipeId: recipeId,
          userId: currentUserId,
          content: commentContent.trim()
        },
        {
          recipe: { id: recipeId },
          user: { id: currentUserId },
          content: commentContent.trim()
        }
      ];

      let success = false;
      
      for (const body of requestBodies) {
        try {
          const response = await fetch(`/api/recipecomment`, {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
          });

          if (response.ok) {
            message.success('评论发布成功');
            setCommentContent('');
            await fetchComments();
            success = true;
            break;
          }
        } catch (error) {
          continue;
        }
      }

      if (!success) {
        message.error('发布评论失败，请稍后重试');
      }

    } catch (error) {
      console.error('发布评论时网络错误:', error);
      message.error('发布评论失败，请检查网络连接');
    } finally {
      setSubmitting(false);
    }
  };

  // 删除评论
  const handleDeleteComment = async (commentId: number) => {
    const token = localStorage.getItem('token');
    if (!token) {
      message.info('请先登录');
      return;
    }

    setDeleteLoading(prev => ({ ...prev, [commentId]: true }));

    try {
      const response = await fetch(`/api/recipecomment?id=${commentId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        message.success('评论删除成功');
        setComments(prev => prev.filter(comment => comment.id !== commentId));
      } else {
        message.error('删除评论失败');
      }
    } catch (error) {
      console.error('删除评论时网络错误:', error);
      message.error('删除评论失败，请检查网络连接');
    } finally {
      setDeleteLoading(prev => ({ ...prev, [commentId]: false }));
    }
  };

  // 点赞/取消点赞评论
  const handleLikeComment = async (comment: Comment) => {
    const currentUserId = getCurrentUserId();
    if (!currentUserId) {
      message.info('请先登录');
      return;
    }

    const token = localStorage.getItem('token');
    if (!token) {
      message.info('请先登录');
      return;
    }

    setLikeLoading(prev => ({ ...prev, [comment.id]: true }));

    try {
      if (comment.isLiked) {
        const response = await fetch(`/api/recipecommentlike`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: currentUserId,
            commentId: comment.id
          })
        });

        if (response.ok) {
          setComments(prev => prev.map(c => 
            c.id === comment.id 
              ? { 
                  ...c, 
                  isLiked: false, 
                  likeCount: Math.max(0, c.likeCount - 1) 
                }
              : c
          ));
          message.success('取消点赞');
        } else {
          message.error('取消点赞失败');
        }
      } else {
        const response = await fetch(`/api/recipecommentlike`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            userId: currentUserId,
            commentId: comment.id
          })
        });

        if (response.ok) {
          setComments(prev => prev.map(c => 
            c.id === comment.id 
              ? { 
                  ...c, 
                  isLiked: true, 
                  likeCount: c.likeCount + 1 
                }
              : c
          ));
          message.success('点赞成功');
        } else {
          message.error('点赞失败');
        }
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      message.error('操作失败，请稍后重试');
    } finally {
      setLikeLoading(prev => ({ ...prev, [comment.id]: false }));
    }
  };

  // 处理键盘事件 - 移除换行功能，只保留Enter发布
  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      submitComment();
    }
  };

  useEffect(() => {
    fetchComments();
  }, [recipeId]);

  // 检查当前用户是否是评论的作者
  const isCommentAuthor = (comment: Comment) => {
    const currentUserId = getCurrentUserId();
    return currentUserId === comment.user.id;
  };

  if (loading) {
    return (
      <Card
        style={{
          background: 'white',
          borderRadius: '12px',
          border: `1px solid ${colors.border}`,
          padding: '0',
          boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
          height: '600px',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <div style={{ 
          flex: 1, 
          background: 'white',
          borderRadius: '12px',
          padding: '20px',
          display: 'flex', 
          flexDirection: 'column',
          overflow: 'hidden',
          height: '100%'
        }}>
          <div style={{ 
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            height: '100%'
          }}>
            <Spin size="large" style={{ color: colors.primary }} />
            <p style={{ marginTop: 16, color: colors.primaryDark }}>
              正在加载评论...
            </p>
          </div>
        </div>
      </Card>
    );
  }

  return (
    <Card
      style={{
        background: 'white',
        borderRadius: '12px',
        border: `1px solid ${colors.border}`,
        padding: '0',
        boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
        height: '600px',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <div style={{ 
        flex: 1, 
        background: 'white',
        borderRadius: '12px',
        padding: '20px',
        display: 'flex', 
        flexDirection: 'column',
        overflow: 'hidden',
        height: '100%'
      }}>

        <div style={{ marginBottom: '16px' }}>
          <Title 
            level={4} 
            style={{ 
              margin: 0,
              color: colors.primaryDark
            }}
          >
            评论区
          </Title>
          <Text style={{ color: colors.primaryDark, opacity: 0.7 }}>
            共 {comments.length} 条评论
          </Text>
        </div>

        {/* 可滚动的内容区域 */}
        <div style={{ 
          flex: '1 1 auto',
          overflowY: 'auto',
          paddingRight: '10px',
          minHeight: 0,
          maxHeight: '300px'
        }}>
          {/* 评论列表 */}
          <List
            itemLayout="horizontal"
            dataSource={comments}
            renderItem={(item) => (
              <List.Item 
                style={{ 
                  alignItems: 'flex-start',
                  padding: '12px 0',
                  borderBottom: `1px solid ${colors.border}`
                }}
                actions={[
                  <Tooltip key="like" title={item.isLiked ? '取消点赞' : '点赞'}>
                    <Button
                      type="text"
                      size="small"
                      icon={item.isLiked ? <LikeFilled style={{ color: '#ff4d4f' }} /> : <LikeOutlined />}
                      loading={likeLoading[item.id]}
                      onClick={() => handleLikeComment(item)}
                      style={{
                        color: item.isLiked ? '#ff4d4f' : colors.primaryDark,
                        fontSize: '12px'
                      }}
                    >
                      {item.likeCount || 0}
                    </Button>
                  </Tooltip>,
                  
                  isCommentAuthor(item) && (
                    <Popconfirm
                      key="delete"
                      title="确定要删除这条评论吗？"
                      onConfirm={() => handleDeleteComment(item.id)}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Tooltip title="删除评论">
                        <Button
                          type="text"
                          size="small"
                          icon={<DeleteOutlined />}
                          loading={deleteLoading[item.id]}
                          style={{
                            color: '#ff4d4f',
                            fontSize: '12px'
                          }}
                        />
                      </Tooltip>
                    </Popconfirm>
                  )
                ].filter(Boolean)}
              >
                <List.Item.Meta
                  avatar={
                    <Avatar
                      src={item.user.avatar || 'https://picsum.photos/30/30?random=1'}
                      size="small"
                    />
                  }
                  title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <Text strong style={{ color: colors.primaryDark }}>
                        {item.user.username}
                      </Text>
                      {isCommentAuthor(item) && (
                        <Text style={{ 
                          fontSize: '10px', 
                          color: colors.badge,
                          background: colors.background,
                          padding: '2px 6px',
                          borderRadius: '8px'
                        }}>
                          作者
                        </Text>
                      )}
                    </div>
                  }
                  description={
                    <>
                      <div style={{ 
                        wordBreak: 'break-word', 
                        whiteSpace: 'normal',
                        overflowWrap: 'break-word',
                        maxWidth: '100%',
                        lineHeight: '1.5',
                        color: colors.primaryDark,
                        marginBottom: '4px'
                      }}>
                        {item.content}
                      </div>
                      <Text style={{ 
                        fontSize: '12px', 
                        color: colors.primaryDark,
                        opacity: 0.7
                      }}>
                        {formatDate(item.createdAt)}
                      </Text>
                    </>
                  }
                />
              </List.Item>
            )}
            locale={{
              emptyText: (
                <div style={{ 
                  textAlign: 'center', 
                  padding: '40px 0',
                  color: colors.primaryDark,
                  opacity: 0.7
                }}>
                  暂无评论，快来发表第一条评论吧~
                </div>
              )
            }}
          />
        </div>

        {/* 固定在底部的发表评论输入框 */}
        <div style={{ 
          marginTop: '16px', 
          padding: '16px', 
          background: colors.background, 
          borderRadius: '8px',
          border: `1px solid ${colors.border}`,
          alignSelf: 'stretch',
        }}>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
            <Button
              type="primary"
              size="small"
              disabled={!localStorage.getItem('token') || submitting || !commentContent.trim()}
              onClick={submitComment}
              loading={submitting}
              style={{
                backgroundColor: colors.primary,
                borderColor: colors.primary,
                color: colors.primaryDark,
                borderRadius: '16px',
                fontWeight: 'bold'
              }}
            >
              {submitting ? '发布中...' : '发表评论'}
            </Button>
          </div>
          <Input.TextArea 
            placeholder={localStorage.getItem('token') ? "留下你的想法吧~~" : "请先登录后发表评论"}
            rows={3} 
            disabled={!localStorage.getItem('token') || submitting}
            value={commentContent}
            onChange={(e) => setCommentContent(e.target.value)}
            onKeyDown={handleKeyPress}
            style={{ 
              fontSize: '14px',
              border: `1px solid ${colors.border}`,
              borderRadius: '8px'
            }}
          />
        </div>
      </div>
    </Card>
  );
};

export default RecipeComments;